<template>
    <div>
        <div class="license" v-if="showLicense">
            <span>营业执照</span>
            <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <el-icon v-if="loading" class="is-loading avatar-uploader-icon">
                    <Loading />
                </el-icon>
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
            <el-button @click="exmpleVisible = true">查看示例</el-button>
        </div>
        <el-form :model="form" ref="ruleFormRef" :rules="rules" :inline="true" v-else>
            <div class="formitem">
                <div class="label" style="margin-top: 6px;"><span>*</span>企业名称</div>
                <el-form-item prop="name" style="width: 100%;">
                    <el-input v-model="form.name" style="width: 100%;" />
                </el-form-item>
            </div>
            <div class="formitem">
                <div class="label" style="margin-top: -4px;"><span>*</span>统一社会信用代码或工商注册号</div>
                <el-form-item prop="social_credit_code" style="width: 100%">
                    <el-input v-model="form.social_credit_code" style="width: 100%;" />
                </el-form-item>
            </div>
            <div class="formitem">
                <div class="label" style="margin-top: 6px;"><span>*</span>法定代表人姓名</div>
                <el-form-item prop="legal_person" style="width: 100%">
                    <el-input v-model="form.legal_person" style="width: 100%;" />
                </el-form-item>
            </div>
            <el-form-item style="width: 100%;">
                <el-button class="submit" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
            </el-form-item>
        </el-form>
        <div class="change" v-if="showLicense" @click="showLicense = false">
            营业执照无法识别？<span>手动填写</span></div>
        <div class="change" v-else @click="showLicense = true">切换至<span>营业执照识别</span></div>
        <el-dialog v-model="exmpleVisible" title="营业执照示例" width="500">
            <img src="../../../assets/enterprise/example.png" style="width: 100%;">
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { baseURL } from '@/api/index'
import { LicenseOcr } from '@/api/enterprise'
import { useCompanyDataStore } from '@/store/companys'

const companyDataStore = useCompanyDataStore()

const validateSocialCreditCode = (rule: any, value: string, callback: any) => {
    const creditCodeRegex = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/
    const regNumberRegex = /^\d{15}$/

    if (!value) {
        callback(new Error('统一社会信用代码或工商注册号'))
    } else if (!creditCodeRegex.test(value) && !regNumberRegex.test(value)) {
        callback(new Error('格式错误：需18位信用代码或15位注册号'))
    } else {
        callback()
    }
}

const form = reactive({
    name: '',
    social_credit_code: '',
    legal_person: '',
    id: companyDataStore.certifyCompany?.id
})
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()
const rules = reactive({
    name: [
        { required: true, message: '请输入企业名称', trigger: 'blur' }
    ],
    social_credit_code: [
        {
            required: true,
            validator: validateSocialCreditCode,
            trigger: ['blur', 'change']
        }
    ],
    legal_person: [
        { required: true, message: '请输入法定代表人姓名', trigger: 'blur' }
    ],
})
const showLicense = ref(true)
const exmpleVisible = ref(false)
const uploadUrl = baseURL + '/admin/Ajax/upload'

const emit = defineEmits(['submit-success'])

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    LicenseOcr({
        url: response.data.url
    }).then(res => {
        form.name = res.data.companyName
        form.social_credit_code = res.data.creditCode
        form.legal_person = res.data.legalPerson
        loading.value = false
        showLicense.value = false
    }).catch(() => {
        loading.value = false
    })
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    loading.value = true
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('请上传jpg或png格式的图片')
        loading.value = false
        return false
    } else if (rawFile.size / 1024 / 1024 > 20) {
        ElMessage.error('图片大小不能大于20MB!')
        loading.value = false
        return false
    }
    return true
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            emit('submit-success', {
                ...form
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style scoped lang="scss">
.formitem {
    width: 100%;
    display: flex;
    margin-bottom: 15px;

    .label {
        width: 136px;
        text-align: right;
        margin-right: 16px;
        line-height: 20px;
        font-size: 14px;
        color: #666;
        flex-shrink: 0;

        span {
            color: #f00;
        }
    }
}

.submit {
    width: 200px;
    height: 37px;
    color: #fff;
    background-color: #01509f;
    margin: 25px auto 0;
}

.change {
    font-size: 14px;
    text-align: center;
    margin-top: 10px;

    span {
        color: #01509f;
        cursor: pointer;
    }
}

.license {
    width: 466px;
    margin: 0 auto;
    display: flex;
    align-items: flex-end;

    span {
        font-size: 14px;
        color: #666;
        height: 178px;
    }

    .avatar-uploader {
        width: 288px;
        height: 178px;
        margin: 0 16px;

        .avatar {
            width: 288px;
            height: 178px;
            display: block;
        }

        :deep(.el-upload) {
            width: 286px;
            height: 176px;
            border: 1px dashed #ddd;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 38px;
            color: #ccc;
            width: 288px;
            height: 178px;
            text-align: center;
        }

        .el-icon.is-loading {
            animation: rotating 2s linear infinite;
        }

        @keyframes rotating {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }
    }

}
</style>